import { existplayer,Read_player,Write_player,Add_player,__PATH,get_player_img,Write_json,Read_json
    ,alluser,Go,Go2,getPlayerAction,isNotNull,getGuojiaIndex,getGuojia,hasPassedOneDay,getfuben } from "../game/sanguo.js";
import data from '../../model/sanguoData.js'
import fs from 'fs';
import Show from '../../model/show.js';
let shi ={
 "名字":"无",         
 "诗词":"poem",
 "品级":"pinji",
 "评论":[]
 }
export class tishi extends plugin {
    constructor() {
      super({
        /** 功能名称 */
        name: '三国|题诗模块',
        /** 功能描述 */
        dsc: '题诗模块',
        event: 'message',
        /** 优先级，数字越小等级越高 */
        priority: 600,
        rule: [
          {
            reg: /^(#|\/)题诗.*$/,
            fnc: 'ti',
          },
          {
            reg: /^(#|\/)评价.*$/,
            fnc: 'p',
          },
          {
            reg: /^(#|\/)我的诗.*$/,
            fnc: 'my',
          },
          {
            reg: /^(#|\/)他的诗.*$/,
            fnc: 'ta',
          },
          {
            reg: /^(#|\/)查看自己诗词(内容|评论).*$/,
            fnc: 'check',
          },
          {
            reg: /^(#|\/)查看他人诗词(内容|评论).*$/,
            fnc: 'check2',
          }
        ]
      });
    }
    async ta(e){
      const usr_qq = e.user_id;  
      const atItems = e.message.filter(item => item.type === 'at');
      if (!atItems) return;
      const B_qq = atItems[0].qq;
      if (!(await existplayer(1, B_qq))) return;
      let player = await Read_player(1, B_qq);
      let get_data={shi: player.诗}
      const data1 = await new Show().get_shi(get_data);
      let img = await puppeteer.screenshot('shi', {
          ...data1,
      });
      return e.reply(img);
    }
    async check2(e){
      const usr_qq = e.user_id;
      const atItems = e.message.filter(item => item.type === 'at');
      if (!atItems) return;
      const B_qq = atItems[0].qq;
      if (!(await existplayer(1, B_qq))) return;
      let player = await Read_player(1, B_qq);
      const name = e.msg.replace(/\/查看他人诗词(内容|评论)|#查看他人诗词(内容|评论)/g, '').trim();
      let x = player.诗.find(item => item.名字 === name);
      if (!x) return e.reply(`没有这个诗词`);
      let type = null;
      if (/内容/.test(e.msg)) type = 'get_shici'; 
      else if (/评论/.test(e.msg)) type = 'get_shilun';
      if (!type) return e.reply('无法确定要获取的内容类型');
      let get_data = { shi: x, usr_qq: B_qq };
      const data1 = await new Show()[type](get_data);
      let img = await puppeteer.screenshot('shi', { ...data1 });
      return e.reply(img);
    } 

    // async check2(e){
    //   const usr_qq = e.user_id;
    //   if (!(await existplayer(1, usr_qq))) return;
    //   let player = await Read_player(1, usr_qq);
    //   const name = e.msg.replace(/\/查看自己诗词评论|#查看自己诗词评论/g, '').trim();
    //   console.log(name);
    //   let x = player.诗.find(item => item.名字 === name)
    //   if(!x) return e.reply(`没有这个诗词`)
    //   let get_data={shi: x ,usr_qq:usr_qq}
    //   const data1 = await new Show().get_shilun(get_data);
    //   let img = await puppeteer.screenshot('shi', {
    //       ...data1,
    //   });
    //   return e.reply(img);
    // }
    // async check(e){
    //   const usr_qq = e.user_id;
    //   if (!(await existplayer(1, usr_qq))) return;
    //   let player = await Read_player(1, usr_qq);
    //   const name = e.msg.replace(/\/查看自己诗词内容|#查看自己诗词内容/g, '');
    //   let x = player.诗.find(item => item.名字 === name)
    //   if(!x) return e.reply(`没有这个诗词`)
    //   let get_data={shi: x ,usr_qq:usr_qq}
    //   const data1 = await new Show().get_shici(get_data);
    //   let img = await puppeteer.screenshot('shi', {
    //       ...data1,
    //   });
    //   return e.reply(img);
    // }
    async check(e) {
      const usr_qq = e.user_id;
      if (!(await existplayer(1, usr_qq))) return;
      let player = await Read_player(1, usr_qq);
      const name = e.msg.replace(/\/查看自己诗词(内容|评论)|#查看自己诗词(内容|评论)/g, '').trim();
      let x = player.诗.find(item => item.名字 === name);
      if (!x) return e.reply(`没有这个诗词`);
      let type = null;
      if (/内容/.test(e.msg)) type = 'get_shici'; 
      else if (/评论/.test(e.msg)) type = 'get_shilun';
      if (!type) return e.reply('无法确定要获取的内容类型');
      let get_data = { shi: x, usr_qq: usr_qq };
      const data1 = await new Show()[type](get_data);
      let img = await puppeteer.screenshot('shi', { ...data1 });
      return e.reply(img);
    }
    
    async my(e){
      const usr_qq = e.user_id;
      if (!(await existplayer(1, usr_qq))) return;
      if (!e.isGroup) return;
        let player = await Read_player(1, usr_qq);
        let get_data={shi: player.诗}
        const data1 = await new Show().get_shi(get_data);
        let img = await puppeteer.screenshot('shi', {
            ...data1,
        });
        return e.reply(img);
    }
    async p(e){
      const usr_qq = e.user_id;
      if (!(await existplayer(1, usr_qq))) return;
      const name = e.msg.replace(/\/评价|#评价/g, '');
      const atItems = e.message.filter(item => item.type === 'at');
      if (!atItems) return;
      const B_qq = atItems[0].qq;
      let player = await Read_player(1, B_qq);
      let [名字, 评价] = name.split('*');
      let shi = player.诗.find(item => item.名字 === 名字);
      if (!shi) return e.reply(`对方没有这种诗`);
      let msg = 评价 + `(来自${usr_qq})`
      shi.评论.push(msg);
      await Write_player(1,usr_qq,player)
      return e.reply(`评价成功`);
    }
    async ti(e){
        const usr_qq = e.user_id;
        let player = await Read_player(1, usr_qq);
        const name = e.msg.replace(/\/题诗|#题诗/g, '');
        const poem = name; // 从用户输入中获取诗词
        let pan;
        const { sentences, isRhymeSame } = extractSentences(poem);
        console.log(sentences);
        if (isRhymeSame) {
            console.log('韵母相同') 
            pan = true
        }
        console.log(isRhymeSame);
        const sentences2 = poem.split(',').map(sentence => sentence.trim()); // 使用逗号分割诗词成句子数组，并去除每个句子前后的空格
        const chang = sentences2.length
        if( chang === 1) return e.reply(`单字成诗?`)
        e.reply(`开始评级`)
        const pinji = pingji(poem,chang,isRhymeSame)
        e.reply(`评级成功,级别为${pinji}`)
        const response = `您的诗词包含以下句子：\n${sentences.join('\n')}}`;
        console.log(response);
        await e.reply('请输入你诗的名称', false, {
            at: true,
        });
        shi.诗词 = poem
        shi.品级 = pinji
        this.setContext('m');
        return 
        }
    async m(e){
        const usr_qq = e.user_id;
        let player = await Read_player(1, usr_qq);
        var reg = new RegExp(/.*/);
        let new_msg = this.e.msg, difficulty = reg.exec(new_msg);
        if(player.诗.find(team => team.名字 ===difficulty[0] )){
            await e.reply('此名字已有,请重新输入你诗的名称', false, {
                at: true,
            });
            this.finish('m')
            this.setContext('m');
            return 
        }
        
        shi.名字 = difficulty[0]
        player.诗.push(shi)
        await Write_player(1,usr_qq,player)
        this.finish('m')
        e.reply(`命名成功，诗的名字为${difficulty[0]}`);
        return;
    }
    }


    function pingji(poem, length, isRhymeSame) {
        // 添加更多的判断条件和指标
        let score = 0;
        // 判断诗歌的长度
        if (length > 10 && length < 20) score += 1;
         else if (length >= 20) score += 2; 
         else score -= 1;
        // 判断诗歌的押韵情况
        if (isRhymeSame) score += 1;
         else score -= 1;
        // 根据得分给出评价
        if (score >= 2) return '高级诗';
         else if (score >= 0) return '中级诗'; 
         else  return '低级诗';
    }    
 
//   function extractSentences(poem) {
//     if (!poem) {
//       return {
//         sentences: [],
//         isRhymeSame: false
//       };
//     }
  
//     const sentences = poem.split(',').map(sentence => sentence.trim()); // 使用逗号分割诗词成句子数组，并去除每个句子前后的空格
  
//     const rhymePattern = /[aeiouü]?([a-zA-Z]+)[^aeiouü]?$/; // 用于提取最后一个韵母的正则表达式
  
//     const rhymes = sentences.map(sentence => {
//       const match = sentence.match(rhymePattern);
//       return match ? match[1] : ''; // 提取最后一个韵母，如果匹配失败则返回空字符串
//     });
  
//     const isRhymeSame = rhymes.every((rhyme, index, array) => rhyme === array[0]); // 判断所有韵母是否相同
  
//     // 返回处理后的句子数组和韵母是否相同的标志
//     return {
//       sentences,
//       isRhymeSame
//     };
//   }
  function extractSentences(poem) {
    if (!poem) {
        return {
          sentences: [],
          isRhymeSame: false
        };
      }
      
      const sentences = poem.split(/[.!?\uff01\uff1f]/).map(sentence => sentence.trim()); // 使用句号、感叹号和问号分割诗词成句子数组，并去除每个句子前后的空格
      
      const rhymePattern = /[a-zA-Z]$/; // 用于提取句号、感叹号和问号前的一个字的韵母的正则表达式
      
      const rhymes = sentences.map(sentence => {
        const match = sentence.match(rhymePattern);
        return match ? match[0] : ''; // 提取句号、感叹号和问号前的一个字的韵母，如果匹配失败则返回空字符串
      });
      
      const isRhymeSame = rhymes.every((rhyme, index, array) => {
        if (index === 0) {
          return true; // 第一个句子无需比较，直接返回 true
        }
        
        const previousSentence = sentences[index - 1];
        const hasPunctuation = /[.!?\uff01\uff1f]$/.test(previousSentence); // 判断前一个句子是否以句号、感叹号或问号结尾
        return hasPunctuation ? rhyme === array[index - 1] : true; // 只在前一个句子有标点符号时进行韵母比较
      });
      
      // 返回处理后的句子数组和韵母是否相同的标志
      return {
        sentences,
        isRhymeSame
      };   
  }